import { HttpException, Injectable } from '@nestjs/common';
import { CreateFriendsShipDto } from './dto/create-friends-ship.dto';

import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class FriendsShipService {
  constructor(private readonly prismaService: PrismaService) {}
  async create(createFriendsShipDto: CreateFriendsShipDto, userId: number) {
    const res = await this.prismaService.friendsRequest.create({
      data: {
        fromUserId: userId,
        toUserId: +createFriendsShipDto.toUserId,
        reason: createFriendsShipDto.reason || null,
      },
    });

    return res;
  }

  async findAll(userId: number) {
    const user = await this.prismaService.friendsShip.findMany({
      where: {
        OR: [
          {
            userId: userId,
          },
          {
            friendId: userId,
          },
        ],
      },
    });

    const set = new Set<number>();
    for (let i = 0; i < user.length; i++) {
      set.add(user[i].userId);
      set.add(user[i].friendId);
    }

    const friendIds = [...set].filter((item) => item !== userId);

    const res = [];

    for (let i = 0; i < friendIds.length; i++) {
      const friend = await this.prismaService.user.findUnique({
        where: {
          id: friendIds[i],
        },
        select: {
          id: true,
          username: true,
        },
      });
      res.push(friend);
    }

    return res;
  }

  async getRequstList(id: number) {
    console.log(id, 'id');
    const res = await this.prismaService.friendsRequest.findMany({
      where: {
        toUserId: id,
        status: 0,
      },
      include: {
        user: {
          select: {
            id: true,
            username: true,
          },
        },
      },
    });

    return res;
  }

  async agree(friendId: number, userId: number) {
    await this.prismaService.friendsRequest.update({
      where: {
        fromUserId_toUserId: {
          fromUserId: friendId,
          toUserId: userId,
        },
        status: 0,
      },

      data: {
        status: 1,
      },
    });

    const res = await this.prismaService.friendsShip.findMany({
      where: {
        OR: [
          {
            friendId: userId,
            userId: friendId,
          },
          {
            friendId: friendId,
            userId: userId,
          },
        ],
      },
    });

    if (res.length) throw new HttpException('Already friends', 400);

    await this.prismaService.friendsShip.create({
      data: {
        friendId: userId,
        userId: friendId,
      },
    });

    return { message: 'Agreed' };
  }

  async refuse(friendId: number, userId: number) {
    console.log(friendId, userId);
    try {
      await this.prismaService.friendsRequest.update({
        where: {
          fromUserId_toUserId: {
            fromUserId: friendId,
            toUserId: userId,
          },
          status: 0,
        },

        data: {
          status: 2,
        },
      });

      return { message: 'Refused' };
    } catch (error) {
      throw new HttpException(error.message, 400);
    }
  }

  // 模糊搜索通过usrename
  async search(username: string) {
    const res = await this.prismaService.user.findMany({
      where: {
        username: {
          contains: username,
        },
      },
      select: {
        id: true,
        username: true,
      },
    });

    return res;
  }
}
